package com.smarthome.api.mobile.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;

import com.alibaba.druid.util.StringUtils;
import com.smarthome.common.exception.SmsException;
import com.smarthome.common.mobile.Service;
import com.smarthome.common.tools.SHACipher;
import com.smarthome.core.account.AccountDoorService;
import com.smarthome.core.account.AccountService;
import com.smarthome.core.account.AccountTypeService;
import com.smarthome.core.housemanager.ResidenceManagerService;
import com.smarthome.core.message.MessageRecordService;
import com.smarthome.core.message.util.MessageUtil;
import com.smarthome.domain.bean.ShAccount;
import com.smarthome.domain.bean.ShAccountDoor;
import com.smarthome.domain.bean.ShSmsRecord;
import com.smarthome.domain.enums.AccountStatus;
import com.smarthome.domain.enums.SmsTypeEnum;
import com.smarthome.domain.mobile.MobileCodeEnum;
import com.smarthome.domain.mobile.MobileResponse;
import com.smarthome.domain.mobile.req.MobileAccountLoginRequest;
import com.smarthome.domain.mobile.req.MobileAccountMobileRegisterRequest;
import com.smarthome.domain.mobile.req.MobileAccountRegisterRequest;
import com.smarthome.domain.mobile.res.MobileAccountLoginResponse;

@org.springframework.stereotype.Service("mobile.account.service")
public class MobileAccountService implements Service<MobileResponse<Map<String, String>>> {

    @Resource
    private AccountService accountService;
    @Resource
    private AccountTypeService accountTypeService;
    @Resource
    private ResidenceManagerService residenceManagerService;
    @Resource
    private MessageRecordService messageRecordService;
    @Resource
    private AccountDoorService accountDoorService;

    /**
     * 获取验证码
     * @param request
     * @param response
     */
    public void getCheckCode(MobileAccountRegisterRequest request, MobileResponse<Map<String, String>> response) {
        Integer doType = request.getDoType();
        if (doType != null) {

            switch (doType) {
            case 1:// 注册验证码
                Map<String, String> ckcode = new HashMap<String, String>();
                ShSmsRecord record = new ShSmsRecord();
                try {
                    // 发送短信，生成记录
                    record = MessageUtil.sendTimelyForCaptcha(SmsTypeEnum.REGIST_VALIDATE_CODE,null, request.getMobile());
                } catch (SmsException e) {
                    e.getExceptionEnum().showMessage();
                    response.setMobileCodeObj(MobileCodeEnum.SMS_SEND_ERROR);
                }
                // 测试时返回验证码
                ckcode.put("ckcode", record.getCaptcha());
                ckcode.put("urid", record.getUrid());
                response.setData(ckcode);
                break;
            case 2:// 找回密码验证码
                String loginName = request.getMobile();
                boolean nameExist = accountService.longinNameExist(loginName);
                if (!nameExist) {
                    response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FOUND);
                } else {
                    Map<String, String> ck_code = new HashMap<String, String>();
                    ShSmsRecord rec = new ShSmsRecord();
                    try {
                        rec = MessageUtil.sendTimelyForCaptcha(SmsTypeEnum.FIND_PASSWORD,null, request.getMobile());
                    } catch (SmsException e) {
                        e.getExceptionEnum().showMessage();
                        response.setMobileCodeObj(MobileCodeEnum.SMS_SEND_ERROR);
                    }
                    ck_code.put("ckcode", rec.getCaptcha());
                    ck_code.put("urid", rec.getUrid());
                    response.setData(ck_code);
                }
                break;
            default:// 找不到操作类型
                response.setMobileCodeObj(MobileCodeEnum.CKCODE_TYPE_ERR);
                break;
            }

        } else {
            response.setMobileCodeObj(MobileCodeEnum.CKCODE_TYPE_ERR);
        }

    }

    /**
     * 注册用户
     * @param request
     * @param response
     */
    public void register(MobileAccountRegisterRequest request, MobileResponse<?> response) {
        boolean vali = MessageUtil.validateCaptcha(request.getCkcode(), request.getUrid());
        if (!vali) {// 验证码不正确
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_CKCODE_ERR);
            return;
        }
        ShAccount reg = new ShAccount();
        BeanUtils.copyProperties(request, reg);
        reg.setLoginName(request.getMobile());
        try {
            reg.setLoginPwd(SHACipher.encrypt(reg.getLoginPwd()));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (StringUtils.isEmpty(reg.getLoginName()) || StringUtils.isEmpty(reg.getLoginPwd()) || StringUtils.isEmpty(reg.getMobile())) {
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FULL);
        } else {
            if (accountService.longinNameExist(reg.getLoginName())) {// 验证登录名是否存在
                response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NAME_EXIST, reg.getLoginName());
            } else {
                try {

                    reg.setTypeId(1L);// 设置注册时默认用户类型
                    reg.setStatus(AccountStatus.NORMAL.getType());// 设置用户状态
                    reg.setHeadImage("head_default.jpg");
                    reg.setSex(1);

                    accountService.add(reg);
                } catch (Exception e) {
                    response.setMobileCodeObj(MobileCodeEnum.SYSTEM_ERROR);
                }

            }
        }

    }

    /**
     * 用户登录
     * @param request
     * @param response
     * @createTime 2015年10月12日 下午9:57:15
     * @author KongXiangyu
     */
    public void login(MobileAccountLoginRequest request, MobileResponse<MobileAccountLoginResponse> response) throws Exception {
        ShAccount account = accountService.queryByNameAndPwd(request.getMobile(), SHACipher.encrypt(request.getLoginPwd()));
        if (null == account||account.getStatus()!=AccountStatus.NORMAL.getType()) {
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_LOGIN_FAIL);
        } else {
            MobileAccountLoginResponse logonRes = new MobileAccountLoginResponse();
            try {
                residenceManagerService.resetResidenceForAccount(account);
                String token = SHACipher.encrypt(account.getMobile());
                logonRes.setAccountId(account.getId());
                logonRes.setHeadImage(account.getHeadImage());
                logonRes.setName(account.getName());
                logonRes.setSex(account.getSex());
                logonRes.setMobile(account.getMobile());
                logonRes.setLoginToken(token);

                ShAccountDoor accountDoor = accountDoorService.getDefaultDoor(account.getId(), account.getResidenceId());
                logonRes.setDoor(accountDoor);

                response.setData(logonRes);
            } catch (Exception e) {
                e.printStackTrace();
            }
            response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_LOGIN_SUC);
        }
    }

    /**
     * 找回密码
     * @param request
     * @param response
     */
    public void rebackPwd(MobileAccountRegisterRequest request, MobileResponse<?> response) {
    	String urid = request.getUrid();
        try {
            boolean vali = MessageUtil.validateCaptcha(request.getCkcode(), urid);
            if (!vali) {
                response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_CKCODE_ERR);
            }else{
            	String loginName = request.getMobile();
                ShAccount account = new ShAccount();
                account.setLoginName(loginName);
                List<ShAccount> queryAccount = accountService.queryAccounts(account);
                if (queryAccount.size() <= 0) {
                    response.setMobileCodeObj(MobileCodeEnum.ACCOUNT_NOT_FOUND);
                } else {
                    account = queryAccount.get(0);
                    account.setLoginPwd(SHACipher.encrypt(request.getLoginPwd()));
                    accountService.edit(account);
                }
            }
        } catch (SmsException e) {
            response.setMobileCodeObj(e.getExceptionEnum().getCodeEnum());
        } catch (Exception e) {
			e.printStackTrace();
		}
    }

    /**
     * 登记手机序号
     * @param request
     * @param response
     */
    public void recordMobile(MobileAccountMobileRegisterRequest request, MobileResponse<?> response) {
        ShAccount account = new ShAccount();
        account.setId(request.getAccountId());
        account.setRegistrationId(request.getRegistrationId());
        accountService.edit(account);
    }
}